
/**
 * Date:2019年5月31日下午2:35:31
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved.
 *
*/

package com.xue.im.common.coder;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.xue.im.common.IMUtil.MessageType;
import com.xue.im.common.vo.Header;
import com.xue.im.common.vo.Message;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

/**
 * Description: 消息编码器 <br/>
 * Date: 2019年5月31日 下午2:35:31 <br/>
 * 
 * @author xuejianxin
 */
public class MessageEncoder extends MessageToMessageEncoder<Message> {
	private final MyMarshallingEncoder marshallingEncoder;

	public MessageEncoder() throws IOException {
		this.marshallingEncoder = new MyMarshallingEncoder();
	}

	@Override
	protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
		if (null == msg || null == msg.getHeader()) {
			throw new RuntimeException("The encode message is null");
		}

		try {

			Header h = msg.getHeader();
			if (h.getType() != MessageType.HEARTBEAT_REQ.value() && h.getType() != MessageType.HEARTBEAT_RESP.value()) {
				System.out.println(">>>>>发出发出发出发出发出发出：" + msg);
			}

			ByteBuf sendBuf = Unpooled.buffer();
			sendBuf.writeInt(h.getCrcCode());// 魔数4
			int lenOffset = sendBuf.readableBytes();
			sendBuf.writeInt(h.getLength());// 消息长度4+4=8
			//sendBuf.writeLong(h.getSessionId());// 会话id8+8=16
			sendBuf.writeByte(h.getType());// 消息类型16+1=17
			//sendBuf.writeByte(h.getPriority());// 优先级17+1=18
			sendBuf.writeInt(h.getOptions().size());// 附件长度18+4=22
			String key = null;
			byte[] keyArray = null;
			Object value = null;
			for (Map.Entry<String, Object> p : h.getOptions().entrySet()) {
				key = p.getKey();
				keyArray = key.getBytes("UTF-8");
				sendBuf.writeInt(keyArray.length);// 键长度
				sendBuf.writeBytes(keyArray);// 键值
				value = p.getValue();
				marshallingEncoder.encode(value, sendBuf);
			}
			// body
			key = null;
			keyArray = null;
			value = null;
			if (null != msg.getBody()) {
				marshallingEncoder.encode(msg.getBody(), sendBuf);
			} else {
				sendBuf.writeInt(0);// 22+4=26
			}
			// 修改消息总的长度
			sendBuf.setInt(lenOffset, sendBuf.readableBytes());
			// 添加到发送队列
			out.add(sendBuf);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

}
